from rest_framework import serializers
from .models import *
from rest_framework.exceptions import ValidationError
from django.db import transaction


class SystemMenSerializer(serializers.ModelSerializer):
    '''
    系统菜单序列化器
    '''

    class Meta:
        model = SystemMen
        fields = '__all__'


class SystemRoleSerializer(serializers.ModelSerializer):
    """
    系统角色序列化器
    """
    menuIds = serializers.ListField(write_only=True)

    class Meta:
        """
        Meta类用于指定序列化器对应的模型及字段
        """
        model = SystemRole
        fields = '__all__'

    def create(self, validated_data):
        """
        创建系统角色及其关联菜单项

        :param validated_data: 校验后的数据，包含角色信息及菜单ID列表
        :return: 创建的角色实例
        """
        menu_ids = validated_data.pop('menuIds', [])
        with transaction.atomic():
            # 创建系统角色实例
            request = self.context['request']
            validated_data['create_by'] = request.user.username
            role = SystemRole.objects.create(**validated_data)
            # 为角色关联菜单项
            for menu_id in menu_ids:
                SystemRoleMenu.objects.create(role_id=role.role_id, menu_id=menu_id)
        return role

    def update(self, instance, validated_data):
        """
        更新系统角色及其关联菜单项

        :param instance: 系统角色实例
        :param validated_data: 校验后的数据，包含更新的角色信息及菜单ID列表
        :return: 更新后的角色实例
        """
        menu_ids = validated_data.pop('menuIds', [])
        with transaction.atomic():
            # 先删除旧的菜单关联

            SystemRoleMenu.objects.filter(role_id=instance.role_id).delete()
            # 更新角色信息
            request = self.context['request']


            for attr, value in validated_data.items():


                setattr(instance, attr, value)

            instance.update_by = request.user.username
            instance.save()
            # 为角色关联新的菜单项
            for menu_id in menu_ids:
                SystemRoleMenu.objects.create(role_id=instance.role_id, menu_id=menu_id)
        return instance

    def delete(self, instance):
        """
        删除系统角色及其关联菜单项

        :param instance: 系统角色实例
        """
        with transaction.atomic():
            # 删除角色关联的菜单项
            SystemRoleMenu.objects.filter(role_id=instance.role_id).delete()
            # 删除角色实例
            instance.delete()


class SysLoginInfoSerializer(serializers.ModelSerializer):
    '''
    系统登录序列化器
    '''

    class Meta:
        model = SysLoginInfo
        fields = '__all__'


class SysOperLogSerializer(serializers.ModelSerializer):
    '''
    系统操作记录序列化器
    '''

    class Meta:
        model = SysOperLog
        fields = '__all__'
